<template>
	<view class="container">
		<view class="top-container"></view>
		<!-- 当前定位区域 -->
		<view class="location-area">
			<text class="location-label">当前定位：</text>
			<text class="location-city">{{ locationCity }}</text>
			<view class="relocate" @click="getLocation">
				<image src="/static/images/3.1-刷新.png" class="refresh-icon" />
				<text>重新定位</text>
			</view>
		</view>

		<!-- 热门城市标签区域 -->
		<view class="hot-city-area">
			<view class="section-title">热门城市</view>
			<view class="hot-city-list">
				<view class="city-tag" v-for="(city, index) in hotCities" :key="index" @click="selectCity(city)">
					{{ city }}
				</view>
			</view>
		</view>

		<!-- 城市列表分组区域 -->
		<view class="city-list-area">
			<view class="city-group" v-for="(group, key) in cityGroups" :key="key">
				<text class="group-title">{{ key }}</text>
				<view class="city-item" v-for="(city, index) in group" :key="index" @click="selectCity(city)">
					{{ city }}
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import QQMapWX from "../../common/qqmap-wx-jssdk.js";
	import cityData from '@/static/data/city-data.json';

	export default {
		data() {
			return {
				hotCities: ['北京市', '上海市', '广州市', '深圳市', '南京市', '武汉市', '郑州市', '成都市', '三亚市', '重庆市', '杭州市', '厦门市'],
				cityGroups: {},
				locationCity: '定位中...',
				qqmapsdk: null // 初始化置空
			}
		},
		onLoad() {
			// 页面加载时获取定位
			this.getLocation();
		},
		created() {
			// 合并原来的两个created生命周期
			// 1. 初始化腾讯地图SDK
			try {
				this.qqmapsdk = new QQMapWX({
					key: 'GNUBZ-FMN6W-OFQR6-Y37QQ-G7OBV-AFFR4' // 替换为你的腾讯地图key
				});
			} catch (e) {
				console.error('腾讯地图SDK初始化失败:', e);
				this.locationCity = '地图服务异常';
			}

			// 2. 处理城市数据
			this.processCityData();
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},

			// 获取当前位置并逆地理解析
			getLocation() {
				// 先检查SDK是否初始化成功
				if (!this.qqmapsdk) {
					this.locationCity = '地图服务未初始化';
					return;
				}

				this.locationCity = '定位中...';

				uni.getLocation({
					type: 'gcj02', // 腾讯地图使用gcj02坐标系
					success: (res) => {
						console.log('获取位置成功:', res);

						// 调用逆地理编码
						this.qqmapsdk.reverseGeocoder({
							location: {
								latitude: res.latitude,
								longitude: res.longitude
							},
							success: (result) => {
								console.log('逆地理编码成功:', result);
								// 提取城市信息（兼容可能的不同返回格式）
								const city = result.result.address_component.city ||
									result.result.address_component.province;
								this.locationCity = city;
							},
							fail: (err) => {
								console.error('逆地理编码失败:', err);
								this.locationCity = '郑州市';
							}
						});
					},
					fail: (err) => {
						console.error('获取位置失败:', err);
						// 根据错误类型显示不同提示
						if (err.errMsg.includes('auth deny')) {
							this.locationCity = '请开启位置权限';
							// 引导用户打开设置页
							uni.showModal({
								title: '权限不足',
								content: '需要获取位置权限才能定位',
								confirmText: '去设置',
								success: (res) => {
									if (res.confirm) {
										uni.openSetting();
									}
								}
							});
						} else {
							this.locationCity = '定位失败';
						}
					}
				});
			},

			processCityData() {
				const groups = {};
				// 遍历省份
				cityData.forEach(province => {
					// 遍历城市
					province.city.forEach(city => {
						const firstLetter = city.firstP; // 城市拼音首字母
						if (!groups[firstLetter]) {
							groups[firstLetter] = [];
						}
						groups[firstLetter].push(city.name); // 添加城市名
					});
				});

				// 按字母顺序排序
				const sortedGroups = {};
				Object.keys(groups).sort().forEach(key => {
					sortedGroups[key] = groups[key];
				});

				this.cityGroups = sortedGroups;
			},

			// 选择城市逻辑
			selectCity(city) {
				uni.showToast({
					title: `已选择城市：${city}`,
					icon: 'none'
				});
				// 传递城市到上一页
				const pages = getCurrentPages();
				if (pages.length > 1) {
					const prevPage = pages[pages.length - 2];
					prevPage.$vm.setSelectedCity(city); // 假设上一页有setSelectedCity方法
					uni.navigateBack();
				}
			}
		}
	}
</script>

<style>
	.container {
		background-color: #F8F8F8;
		min-height: 100vh;
	}

	.top-container {
		background-color: #2176F3;
		height: 350rpx;
	}

	/* 当前定位区 */
	.location-area {
		background-color: #2176F3;
		color: #fff;
		padding: 20rpx 40rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-top: -350rpx;
	}

	.location-label {
		font-size: 28rpx;
	}

	.location-city {
		font-size: 32rpx;
		font-weight: bold;
		margin: 0 20rpx;
		flex: 1;
	}

	.relocate {
		display: flex;
		align-items: center;
		color: #fff;
		font-size: 26rpx;
	}

	.refresh-icon {
		width: 30rpx;
		height: 30rpx;
		margin-right: 10rpx;
	}

	/* 热门城市区 */
	.hot-city-area {
		background-color: #fff;
		border-radius: 20rpx;
		margin: 20rpx;
		padding: 20rpx;
	}

	.section-title {
		font-size: 30rpx;
		font-weight: bold;
		margin: 20rpx;
	}

	.hot-city-list {
		display: flex;
		flex-wrap: wrap;
	}

	.city-tag {
		background-color: #f5f5f5;
		padding: 15rpx 30rpx;
		border-radius: 20rpx;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
		font-size: 28rpx;
		width: 20%;
		text-align: center;
	}

	/* 城市列表区 */
	.city-list-area {
		background-color: #fff;
		border-radius: 20rpx;
		margin: 0 20rpx 20rpx 20rpx;
	}

	.group-title {
		background-color: #f5f5f5;
		padding: 15rpx 20rpx;
		font-size: 28rpx;
		font-weight: bold;
		color: #666;
	}

	.city-item {
		padding: 20rpx;
		border-bottom: 1rpx solid #eee;
		font-size: 28rpx;
	}
</style>